﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Office.Interop.Excel;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;//复杂邮件的使用
using System.Runtime.InteropServices;
//跨进程读取EXcel

namespace Text
{
    class Program
    {
        //创建一个服务器的链接(创建一个对象)
        static SmtpClient sc;
        //= new SmtpClient("smtp.163.com");
        public static void Main(string[] args)
        {
            //发送邮件    
            //首先引入 using Microsoft.Office.Interop.Excel;
            //其他命名空间:using System.Net;     using System.Net.Mail;
            //using System.Net.Mime;//复杂邮件的使用
            //using System.Runtime.InteropServices; //跨进程读取EXcel

            //1读取Excel
            var ExcelApp = Marshal.GetActiveObject("Excel.Application") as Application;
            //拿到活动工作表
            var st = ExcelApp.ActiveSheet as Worksheet;
            //发邮件前建立链接
            MakeSmtpConnection();
            for (int i = 2; i <= 3; i++)
            {
                //发送邮件     第i行第一列 值                                   i 行第2列值
                SendMails((st.Cells[i, 1] as Range).Value, (st.Cells[i, 2] as Range).Value);
            }
            //测试能否拿大单元格数据
            //Console.WriteLine(st.Range["A2"].Value);
            //Console.WriteLine(st.Range["B2"].Value);
          //关闭连接
            sc.Dispose();
        }
        //建立客户端连接
        public static void MakeSmtpConnection()
        {
            //发送到哪里?(发送方)
            //sc.Send();
            //发送服务器:这里使用的是QQ
            sc.Host = "smtp.qq.com";
            //加密传输
            sc.EnableSsl = true;
            //                                          用户名    ,密码(授权码)
            sc.Credentials = new NetworkCredential("541432151@qq.com", "12345");
        }


        /// <summary>
        /// 发送邮件(写好邮件,调用发送方法)
        /// </summary>
        public static void SendMails(string address, string FilePath)
        {
            var mm = new MailMessage();
            //发送方的邮箱 昵称,编码
            mm.From = new MailAddress("541432151@qq.com", "张三", Encoding.UTF8);
            //接受方(可以有多个)
            mm.To.Add(new MailAddress(address));
            //正文编码
            mm.BodyEncoding = Encoding.UTF8;
            mm.Subject = "邮件标题";
            //附件
            mm.Attachments.Add(new Attachment(FilePath));
            SendMail(mm);
            Console.WriteLine(FilePath + "发送成功!");
        }
        /// <summary>
        /// 发送方法
        /// </summary>
        /// <param name="ms"></param>
        static void SendMail(MailMessage ms)
        {
            sc.Send(ms);
        }
    }
}
